<template>
  <div class="page-container-padding">
    <div>
      <el-select v-model="curVarietyCode" filterable size="mini">
        <el-option
          v-for="v in varietyList"
          :key="v.code"
          :value="v.code"
          :label="`${v.name} (${v.code})`"
        />
      </el-select>
      <el-button
        type="primary"
        size="mini"
        style="margin-left: 6px"
        :loading="queryLoading"
        @click="toQueryFormulaGroup"
      >
        查询
      </el-button>
    </div>
    <div class="new-group">
      <div>父级：</div>
      <div class="parent-group">{{ curGroupName }}</div>
      <el-input
        v-model="curNewGroupName"
        placeholder="新建分组，无选择父级时为顶级分组(双击表行选择)"
        style="margin-left: 6px; width: 350px"
        size="mini"
      ></el-input>
      <el-button
        size="mini"
        type="primary"
        style="margin-left: 6px"
        :loading="createNewGroupLoading"
        @click="toCreateNewGroup"
      >
        确定新建
      </el-button>
    </div>
    <div class="header-name">分组列表：</div>
    <div>
      <el-table
        border
        stripe
        lazy
        highlight-current-row
        row-key="id"
        :load="loadChildren"
        :data="groupList"
        @row-dblclick="handleCurrentRow"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="名称" />
        <el-table-column prop="sort_num" label="排序" width="70" />
        <el-table-column label="状态" width="110" align="center">
          <template #default="scope">
            <el-tag
              size="mini"
              :type="scope.row.is_active ? 'success' : 'danger'"
            >
              {{ scope.row.is_active ? '公开' : '隐蔽' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="60" align="center">
          <template #default="scope">
            <el-button type="text" @click="toUpdateGroup(scope.row)">
              编辑
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="header-name">
      <span style="color: #d2291e">{{ curGroupName }}&nbsp;</span>
      <span>公式列表：</span>
      <span>
        <el-button size="mini" type="text" @click="toCreateNewFormula">
          新建公式
        </el-button>
      </span>
    </div>
    <div>
      <el-table
        border
        stripe
        :data="groupIndexList"
        @row-dblclick="dbClickFormulRow"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="名称" />
        <el-table-column prop="formula" label="公式" show-overflow-tooltip />
        <el-table-column
          prop="fma_explain"
          label="说明"
          show-overflow-tooltip
        />
        <el-table-column prop="sort_num" label="排序" width="70" />
        <el-table-column label="状态" width="110" align="center">
          <template #default="scope">
            <el-tag
              size="mini"
              :type="scope.row.is_active ? 'success' : 'danger'"
            >
              {{ scope.row.is_active ? '公开' : '隐蔽' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="60" align="center">
          <template #default="scope">
            <el-button type="text" @click="toUpdateGroupIndex(scope.row)">
              编辑
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="header-name">
      <span>公式候选列：</span>
      <span style="margin-left: 6px">
        <el-input
          v-model="colKeyword"
          placeholder="关键字搜索"
          size="mini"
        ></el-input>
      </span>
      <span style="margin-left: 6px">
        <el-button size="mini" type="primary" @click="toQueryColumns">
          查询
        </el-button>
      </span>
      <span style="margin-left: 6px">
        <span>
          FormulaID=
          <span style="color: #d2291e; font-weight: 600; margin-right: 16px">
            {{ newColumn.formula_id }}
          </span>
        </span>
        <el-button size="mini" type="text" @click="toCreateNewColumn">
          新建
        </el-button>
      </span>
      <span style="margin-left: auto">
        <el-pagination
          layout="prev, pager, next"
          :current-page="colpage"
          :total="colTotalCount"
          @current-change="colPageChange"
        />
      </span>
    </div>
    <div>
      <el-table border stripe :data="formulaColumnList">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="名称" />
        <el-table-column prop="unit" label="单位" />
        <el-table-column
          prop="is_constant"
          label="是否常数"
          width="80"
          align="center"
        >
          <template #default="scope">
            <el-tag
              size="mini"
              :type="scope.row.is_constant ? 'success' : 'danger'"
            >
              {{ scope.row.is_constant ? '是' : '否' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="constant" label="常数值" />
        <el-table-column
          prop="is_index"
          label="是否指标"
          width="80"
          align="center"
        >
          <template #default="scope">
            <el-tag
              size="mini"
              :type="scope.row.is_index ? 'success' : 'danger'"
            >
              {{ scope.row.is_index ? '是' : '否' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="index_id" label="指标ID" width="90" />
        <el-table-column prop="formula_id" label="所属公式" width="90" />
        <el-table-column prop="sort_num" label="排序" width="90" />
        <el-table-column label="操作" width="60" align="center">
          <template #default="scope">
            <el-button type="text" @click="toUpdateColumn(scope.row)">
              编辑
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div style="line-height: 23px">
      <div>设置说明:</div>
      <div>1、新建一个公式，公式计算描述留空</div>
      <div>2、根据新建好的公式ID，配置参与计算的数据列</div>
      <div>
        3、将公式计算描述填写完毕(格式为
        <span style="color: #d2291e">ID_</span>
        具体id)
      </div>
      <div>4、指标列的单位会跟随指标具体的单位显示，可不配置</div>
    </div>
    <!-- 编辑组弹窗 -->
    <el-dialog :visible.sync="editRow.showEdit" title="修改分组">
      <el-form size="mini" label-width="80px">
        <el-form-item label="名称">
          <el-input v-model="editRow.name" />
        </el-form-item>
        <el-form-item label="状态">
          <el-switch
            v-model="editRow.is_active"
            active-text="公开"
            inactive-text="隐蔽"
          />
        </el-form-item>
        <el-form-item label="序号">
          <el-input v-model="editRow.sort_num"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="editRow.showEdit = false">取消</el-button>
        <el-button
          type="primary"
          :loading="editRow.saveLoading"
          @click="toSaveUpdateRow"
        >
          确定保存
        </el-button>
      </div>
    </el-dialog>
    <!-- 编辑组内公式弹窗 -->
    <el-dialog :visible.sync="editGroupIndexRow.showEdit" title="修改组内公式">
      <el-form size="mini" label-width="80px">
        <el-form-item label="名称">
          <el-input v-model="editGroupIndexRow.name"></el-input>
        </el-form-item>
        <el-form-item label="计算描述">
          <el-input
            v-model="editGroupIndexRow.formula"
            placeholder="输入公式计算表达式"
          ></el-input>
        </el-form-item>
        <el-form-item label="公式描述">
          <el-input
            v-model="editGroupIndexRow.fma_explain"
            placeholder="输入公式文字表达式"
          ></el-input>
        </el-form-item>
        <el-form-item label="序号">
          <el-input v-model="editGroupIndexRow.sort_num"></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-switch
            v-model="editGroupIndexRow.is_active"
            active-text="公开"
            inactive-text="隐蔽"
          />
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="editGroupIndexRow.showEdit = false">取消</el-button>
        <el-button
          type="primary"
          :loading="editGroupIndexRow.saveLoading"
          @click="toSaveGroupFormulaRow"
        >
          确定保存
        </el-button>
      </div>
    </el-dialog>
    <!-- 新建组内公式弹窗 -->
    <el-dialog :visible.sync="newIndex.isShow" title="组内新建公式">
      <div style="padding: 8px 10px">
        <el-form size="mini" label-width="80px">
          <el-form-item label="新名称">
            <el-input
              v-model="newIndex.name"
              placeholder="新的指标名称"
            ></el-input>
          </el-form-item>
          <el-form-item label="计算描述">
            <el-input
              v-model="newIndex.formula"
              placeholder="新建时暂留空，设置完计算数据再填写"
            ></el-input>
          </el-form-item>
          <el-form-item label="单位">
            <el-input
              v-model="newIndex.unit"
              placeholder="计算结果的单位"
            ></el-input>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer">
        <el-button @click="newIndex.isShow = false">取消</el-button>
        <el-button
          type="primary"
          :loading="newIndex.saveLoading"
          @click="toSaveNewGroupFormula"
        >
          确定保存
        </el-button>
      </div>
    </el-dialog>
    <!-- 新建公式使用列弹窗 -->
    <el-dialog :visible.sync="newColumn.isShow" title="新建计算列">
      <div style="padding: 8px 10px">
        <el-form size="mini" label-width="80px">
          <el-form-item label="归属公式">
            <div style="color: #d2291e; font-weight: 600">
              {{ newColumn.formula_id }}
            </div>
          </el-form-item>
          <el-form-item label="名称">
            <el-input
              v-model="newColumn.name"
              placeholder="列显示的名称"
            ></el-input>
          </el-form-item>
          <el-form-item label="单位">
            <el-input v-model="newColumn.unit" placeholder="单位"></el-input>
          </el-form-item>
          <el-form-item label="是否常数">
            <div style="display: flex">
              <el-checkbox v-model="newColumn.is_constant"></el-checkbox>
              <el-input
                v-model="newColumn.constant"
                placeholder="为常数时必填"
                style="margin-left: 6px"
              ></el-input>
            </div>
          </el-form-item>
          <el-form-item label="是否指标">
            <div style="display: flex">
              <el-checkbox v-model="newColumn.is_index"></el-checkbox>
              <el-input
                v-model="newColumn.index_id"
                placeholder="为指标时必填，可从后变搜索"
                style="margin-left: 6px"
              ></el-input>
              <el-select
                v-model="newColumn.index_id"
                placeholder="指标搜索"
                filterable
                remote
                style="width: 300px; margin-left: 6px"
                :remote-method="queryIndexesList"
              >
                <el-option
                  v-for="i in indexSelectList"
                  :key="i.id"
                  :value="i.id"
                  :label="i.name"
                ></el-option>
              </el-select>
            </div>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer">
        <el-button @click="newColumn.isShow = false">取消</el-button>
        <el-button
          type="primary"
          :loading="newColumn.saveLoading"
          @click="toSaveNewColumn"
        >
          确定保存
        </el-button>
      </div>
    </el-dialog>
    <!-- 修改公式计算列的弹窗 -->
    <el-dialog :visible.sync="editColumn.showEdit" title="修改信息">
      <el-form size="mini" label-width="80px">
        <el-form-item label="名称">
          <el-input v-model="editColumn.name" />
        </el-form-item>
        <el-form-item label="单位">
          <el-input v-model="editColumn.unit" />
        </el-form-item>
        <el-form-item label="序号">
          <el-input v-model="editColumn.sort_num"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="editColumn.showEdit = false">取消</el-button>
        <el-button
          type="primary"
          :loading="editRow.saveLoading"
          @click="toSaveUpdateColumn"
        >
          确定保存
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
  import { RetrieveVariety } from '@/api/adminRuizhi/common'
  import { RetrieveIndex } from '@/api/adminRuizhi/dataindexlib'
  import {
    RetrieveFormulaGroup,
    CreateFormulaGroup,
    UpdateFormulaGroup,
    GroupFormula,
    CreateGroupFormula,
    UpdateGroupFormula,
    FormulaColumns,
    CreateFormulaColumn,
    UpdateFormulaColumn,
  } from '@/api/adminRuizhi/formula'
  export default {
    data() {
      return {
        varietyList: [],
        curVarietyCode: null,
        groupList: [],
        queryLoading: false,
        editRow: {
          showEdit: false,
          gid: null,
          name: '',
          is_active: null,
          sort_num: null,
          saveLoading: false,
        },
        curNewGroupName: '',
        curGroupId: 0,
        curGroupName: '',
        createNewGroupLoading: false,
        groupIndexList: [],
        editGroupIndexRow: {
          showEdit: false,
          rid: -1,
          sort_num: null,
          is_active: false,
          name: '',
          formula: '',
          fma_explain: '',
          unit: '',
          vcode: '',
          saveLoading: false,
        },
        newIndex: {
          isShow: false,
          name: '',
          formula: '',
          unit: '',
          saveLoading: false,
        },

        colpage: 1,
        colpageSize: 10,
        colTotalCount: 0,
        colKeyword: '',
        formulaColumnList: [],
        indexSelectList: [],
        newColumn: {
          isShow: false,
          formula_id: null,
          name: '',
          unit: '',
          is_constant: false,
          constant: null,
          is_index: false,
          index_id: null,
          saveLoading: false,
        },
        editColumn: {
          rid: -1,
          name: '',
          unit: '',
          sort_num: null,
          showEdit: false,
          saveLoading: false,
        },
      }
    },
    watch: {
      indexSelected(n) {
        console.log(n)
        this.newIndex.alone = `(${n},"line")`
        const obj = this.getSelectedIndexObj(n)
        if (obj) {
          this.newIndex.name = obj.name
        }
      },
    },
    mounted() {
      RetrieveVariety().then((res) => {
        this.varietyList = res.data.data
      })
      this.queryFormulaColumns()
    },
    methods: {
      // 关键字查询指标
      queryIndexesList(keyword) {
        if (keyword.length < 1) return
        RetrieveIndex(keyword).then((res) => {
          const resData = res.data
          this.indexSelectList = resData.data.rows
        })
      },

      // 查询指标候选列
      queryFormulaColumns() {
        FormulaColumns(this.colKeyword, this.colpage, this.colpageSize).then(
          (res) => {
            this.formulaColumnList = res.data.rows
            this.colTotalCount = res.data.total_count
          }
        )
      },

      toQueryColumns() {
        this.colpage = 1
        this.queryFormulaColumns()
      },

      colPageChange(page) {
        this.colpage = page
        this.queryFormulaColumns()
      },

      // 查询数据
      toQueryFormulaGroup() {
        if (!this.curVarietyCode) {
          this.$baseMessage('请先选择品种再查询!', 'error')
          return
        }
        this.groupList = []
        this.queryLoading = true
        RetrieveFormulaGroup(this.curVarietyCode, 0).then((res) => {
          const resData = res.data
          this.groupList = resData.data.map((item) => {
            item.children = []
            item.hasChildren = true
            return item
          })
          this.curGroupId = 0
          this.curGroupName = '无'
          this.queryLoading = false
          this.groupIndexList = []
        })
      },

      // 懒加载子数据
      loadChildren(tree, treeNode, resolve) {
        RetrieveFormulaGroup(this.curVarietyCode, tree.id).then((res) => {
          const resData = res.data
          resolve(
            resData.data.map((item) => {
              item.children = []
              item.hasChildren = true
              return item
            })
          )
        })
      },

      // 设置当前组和查询当前组指标
      handleCurrentRow(crow) {
        this.curGroupId = crow.id
        this.curGroupName = crow.name
        this.curGroupId = crow.id
        this.curGroupName = crow.name
        this.getGroupFormula()
      },

      dbClickFormulRow(crow) {
        this.newColumn.formula_id = crow.id
      },

      // 查询当前分组下的指标
      getGroupFormula() {
        GroupFormula(this.curGroupId).then((res) => {
          this.groupIndexList = res.data.data
        })
      },

      // 新建分组
      toCreateNewGroup() {
        if (!this.curVarietyCode || this.curNewGroupName.length < 1) {
          this.$baseMessage('请先选择品种并输入名称再添加!', 'error')
          return
        }
        const bodyData = {
          name: this.curNewGroupName,
          vcode: this.curVarietyCode,
          parent_id: this.curGroupId,
        }
        this.createNewGroupLoading = true
        CreateFormulaGroup(bodyData).then((res) => {
          this.$baseMessage(res.message, 'success')
          this.toQueryFormulaGroup()
          this.createNewGroupLoading = false
        })
      },

      toUpdateGroup(row) {
        this.editRow.gid = row.id
        this.editRow.name = row.name
        this.editRow.sort_num = row.sort_num
        this.editRow.is_active = row.is_active
        this.editRow.showEdit = true
      },

      toSaveUpdateRow() {
        const bodyData = {
          gid: this.editRow.gid,
          name: this.editRow.name,
          sort_num: this.editRow.sort_num,
          is_active: this.editRow.is_active ? 1 : 0,
        }
        this.editRow.saveLoading = true
        UpdateFormulaGroup(bodyData).then((res) => {
          this.editRow.saveLoading = false
          this.editRow.showEdit = false
          this.$baseMessage(res.message, 'success')
          this.toQueryFormulaGroup()
        })
      },

      // 获取弹窗选择指标等待新建的对象
      getSelectedIndexObj(iid) {
        let obj = null
        for (let i = 0; i < this.indexSelectList.length; i++) {
          if (this.indexSelectList[i].id === iid) {
            obj = this.indexSelectList[i]
            break
          }
        }
        return obj
      },

      // 准备编辑组内的指标配置
      toUpdateGroupIndex(row) {
        this.editGroupIndexRow.rid = row.id
        this.editGroupIndexRow.name = row.name
        this.editGroupIndexRow.sort_num = row.sort_num
        this.editGroupIndexRow.formula = row.formula
        this.editGroupIndexRow.fma_explain = row.fma_explain
        this.editGroupIndexRow.unit = row.unit
        this.editGroupIndexRow.is_active = row.is_active
        this.editGroupIndexRow.vcode = row.vcode
        this.editGroupIndexRow.showEdit = true
      },

      // 保存组内的指标配置
      toSaveGroupFormulaRow() {
        const bodyData = { ...this.editGroupIndexRow }
        UpdateGroupFormula(bodyData).then((res) => {
          this.$baseMessage(res.message, 'success')
          this.editGroupIndexRow.rid = 0
          this.editGroupIndexRow.showEdit = false
          this.getGroupFormula()
        })
      },

      // 准备在组内新建公式
      toCreateNewFormula() {
        if (this.curGroupId < 1 || !this.curVarietyCode) {
          this.$baseMessage('请先选择品种和双击选择组后再新建!')
          return
        }
        this.newIndex.isShow = true
      },
      // 保存组内新建的公式
      toSaveNewGroupFormula() {
        const bodyData = {
          name: this.newIndex.name,
          formula: this.newIndex.formula,
          unit: this.newIndex.unit,
          vcode: this.curVarietyCode,
          gid: this.curGroupId,
        }
        this.newIndex.saveLoading = true
        CreateGroupFormula(bodyData).then((res) => {
          this.$baseMessage(res.message, 'success')
          this.getGroupFormula()
          this.newIndex.isShow = false
          this.newIndex.saveLoading = false
        })
      },

      // 新建列
      toCreateNewColumn() {
        if (!this.newColumn.formula_id) {
          this.$baseMessage('请先双击选择公式再创建!', 'error')
          return
        }
        this.newColumn.isShow = true
      },

      toSaveNewColumn() {
        this.newColumn.saveLoading = true
        CreateFormulaColumn(this.newColumn)
          .then((res) => {
            console.log(res)
            this.colpage = 1
            this.queryFormulaColumns()
            this.newColumn.formula_id = null
            this.newColumn.isShow = false
            this.newColumn.saveLoading = false
            this.$baseMessage(res.message, 'success')
          })
          .catch(() => {
            this.newColumn.saveLoading = false
          })
      },

      // 修改列
      toUpdateColumn(row) {
        this.editColumn.rid = row.id
        this.editColumn.name = row.name
        this.editColumn.unit = row.unit
        this.editColumn.sort_num = row.sort_num
        this.editColumn.showEdit = true
      },
      toSaveUpdateColumn() {
        this.editColumn.saveLoading = true
        const bData = {
          rid: this.editColumn.rid,
          name: this.editColumn.name,
          unit: this.editColumn.unit,
          sort_num: this.editColumn.sort_num,
        }
        UpdateFormulaColumn(bData).then((res) => {
          this.$baseMessage(res.message, 'success')
          this.editColumn.saveLoading = false
          this.editColumn.showEdit = false
          this.editColumn.rid = -1
          this.queryFormulaColumns()
        })
      },
    },
  }
</script>
<style scoped lang="scss">
  .new-group {
    display: flex;
    align-items: center;
    margin-top: 8px;
    .parent-group {
      color: #ed2400;
      font-weight: 600;
    }
  }
  .header-name {
    margin: 8px 0;
    color: #349cfc;
    font-weight: 600;
    display: flex;
    align-items: center;
  }
  .select-index {
    display: flex;
    align-items: center;
  }
</style>
